package com.alliky.core.loader;

import android.content.Context;
import android.os.Handler;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatDialog;

import com.alliky.core.R;
import com.alliky.core.config.AppConfig;
import com.alliky.core.utils.RxUtils;

import java.util.ArrayList;

/**
 * Author wxianing
 * date 2018/6/26
 */
public class Loader {

    private static final ArrayList<AppCompatDialog> LOADERS = new ArrayList<>();

    private static final String MESSAGE = "正在加载";
    private static final Handler HANDLER = AppConfig.getHandler();
    private static final long DELAYED = 800;

    public static void showLoading(Context context, String message) {
        stopLoading();
        final AppCompatDialog dialog = new AppCompatDialog(context, R.style.dialog_loading);
        dialog.setContentView(R.layout.loading_layout);

        TextView tvMessage = dialog.findViewById(R.id.tv_message);

        if (!RxUtils.isBlank(message)) {
            tvMessage.setText(message);
        }

        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
//        dialog.setCanceledOnTouchOutside(true);
        LOADERS.add(dialog);
        dialog.show();
    }

    public static void showLoading(Context context) {
        showLoading(context, MESSAGE);
    }

    public static void stopLoading() {
        HANDLER.postDelayed(new Runnable() {
            @Override
            public void run() {
                for (AppCompatDialog dialog : LOADERS) {
                    if (dialog != null) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }
                }
            }
        }, DELAYED);
    }
}
